﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
using QzEbook.BaseView;
using QzEbook.Common.Emum;
using QzEbook.AccessObject;
using QzEbook.Common;

namespace qzEbook.webUI
{
    public partial class DefaultSet : UserPage
    {
        private int bookId;
        private int action;

        protected void Page_Load(object sender, EventArgs e)
        {
            titleTb.Focus();
            if (Request["Bid"] != null)
            {
                Session["Action"] = (int)BookAction.Edit;
                bookId = int.Parse(Request["Bid"]);
                Session["ToImageGalleryID"] = bookId;
            }

            if (!IsPostBack)
            {
                setDefault();
            }

        }

        private void setDefault()
        {
            errorLb.Text = "";
            editorTb.Text = userSession.Name;
            editorTb.Enabled = false;
            SiteUser currentUser = getUserInfo();
            if (UserLevel.getLevelByName(currentUser.LevelName) > UserLevel.getLevelByName(UserLevel.Member) || UserLevel.getLevelByName(currentUser.LevelName) == 0)
            {
                priceTb.Enabled = true;
            }

            action = int.Parse(Session["Action"].ToString());
            switch (action)
            {
                case (int)BookAction.AddOne:
                    AddNewOneAction();
                    break;
                case (int)BookAction.Edit:
                    EditAction();
                    break;
            }
        }


        private void EditAction()
        {
            AddOneBookBtn.Enabled = AddOneBookBtn.Visible = false;
            UpDateBookBtn.Enabled = UpDateBookBtn.Visible = true;

            bindData();
        }

        /// <summary>
        /// 当为编辑进入时,进行默认绑定;
        /// </summary>
        private void bindData()
        {
            

            Book book = new Book();
            book.BookId = bookId;
            book= book.select();

            if (book == null)
            {
                Response.Clear();
                Response.Write("不存在book的id为" + bookId);
                Response.End();
            }
            //判断当前用户是否可修当然的页面;
            if (book.EditorId != userSession.Uid)
            {
                Response.Clear();
                Response.Write("你不能有想篡改别人的作品想法");
                Response.End();
            }
            titleTb.Text = book.Title;
            BookContentFtb.Text = book.Content;
            widthTb.Text = book.Width.ToString();
            heightTb.Text = book.Height.ToString();

            string thumb = string.Format("../{0}{1}", Config.UserBookSavePath, book.Thumb);

            if (!string.IsNullOrEmpty(book.Thumb) && File.Exists(Server.MapPath(thumb)))
            {
                thumbImgLb.Visible = true;
                thumbImgLb.Text = string.Format("<img src={0}?rnd={1} alt='书封面' rel='simplebox' /><br />", thumb,DateTime.Now.Second);
            }

            string bgPath = String.Format("../{0}{1}", Config.UserBookSavePath, book.Bg.Path);
            if (!string.IsNullOrEmpty(book.Bg.Path) && File.Exists(Server.MapPath(bgPath)))
            {
                bgImgLb.Visible = true;
                bgImgLb.Text = string.Format("<img src='getBitmap.xhtml?path={0}' href='{0}' alt='背景' rel='simplebox' /><br />", bgPath);
            }

            viewTypeRbl.SelectedValue= book.ViewType==true?"1":"0";
            isVisibleRbl.SelectedValue = book.IsVisible==true?"1":"0";
            auditingRbl.SelectedValue = book.Auditing.ToString();
            priceTb.Text = book.Price.ToString();


            repeaterCb.Checked = book.Bg.Repeat;
            bgSoundTb.Text = book.BgSound.Path;
            loopCb.Checked = book.BgSound.Loop;

            Session["oldTagList"]=book.OldTagList;
            StringBuilder tagsb = new StringBuilder();
            foreach (Tag tag in book.OldTagList)
            {
                tagsb.AppendFormat("{0},",tag.Name);   
            }
            tagTb.Text = tagsb.ToString().TrimEnd(',');
            
            this.bindAlphaList(book.Bg.Alpha);
            this.bindCategoryList(book.CategoryId);
        }

        /// <summary>
        /// 绑定到电子书上面,以便更新或插入;
        /// </summary>
        /// <returns></returns>
        private Book bindBook()
        {
            string spliteStr = ",.，:/;'";
            string[] tagStringList = tagTb.Text.Trim().Split(spliteStr.ToCharArray());
            StringBuilder keySb = new StringBuilder();
            List<Tag> tagList = new List<Tag>(tagStringList.Length);
            foreach (string item in tagStringList)
            {
                string itemname = item.Trim();
                if (String.IsNullOrEmpty(itemname))
                {
                    continue;
                }
                Tag tag = new Tag();
                tag.Name = itemname;
                tagList.Add(tag);
            }

            Book book = new Book();
            book.EditorId = userSession.Uid;
            book.CategoryId = int.Parse(CategoryDdl.SelectedItem.Value);
            book.BookId = bookId;

            book.Title = titleTb.Text.Trim();
            book.OldTagList = Session["oldTagList"] as List<Tag>;
            book.TagList = tagList;
            book.Content = BookContentFtb.Text;

            book.Thumb = getUserBookDirectory(false) + "thumb.jpg";

            book.Bg.Path = getUserBookDirectory(false) + "bg.jpg";
            book.Bg.Alpha = int.Parse(alphaDdl.SelectedItem.Text);
            book.Bg.Repeat = repeaterCb.Checked;

            book.ViewType = viewTypeRbl.SelectedValue == "1";
            book.IsVisible = isVisibleRbl.SelectedValue == "1";
            book.Auditing = int.Parse(auditingRbl.SelectedValue);
            book.Price = int.Parse(priceTb.Text.Trim());

            book.Width = int.Parse(widthTb.Text.Trim());
            book.Height = int.Parse(heightTb.Text.Trim());

            book.BgSound.Path = bgSoundTb.Text.Trim();
            book.BgSound.Loop = loopCb.Checked;

            return book;
        }

        /// <summary>
        /// 以添加电子书进入;
        /// </summary>
        private void AddNewOneAction()
        {
            AddOneBookBtn.Enabled = AddOneBookBtn.Visible = true;
            UpDateBookBtn.Enabled = UpDateBookBtn.Visible = false;
            

            this.bindAlphaList(100);
            this.bindCategoryList(1);
        }


        /// <summary>
        /// 新增一本杂志;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AddOneBookBtn_Click(object sender, EventArgs e)
        {
            if (action == (int)BookAction.Edit)
            {
                alert("不要重复提交");
                return;
            }
            Book book = this.bindBook();
            bookId = -1;
            bool result = book.insert(ref bookId);
            if (result)
            {
                string path = getUserBookDirectory(true);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                this.savePicture();
                AddOneBookBtn.Enabled = AddOneBookBtn.Visible = false;
                Response.Redirect(String.Concat("PageList.xhtml?Bid=", bookId));
            }
            else
            {
                errorLb.Text = "添加失败";
            }

        }


        /// <summary>
        /// 绑定背景透明度值;
        /// </summary>
        /// <param name="alpha"></param>
        private void bindAlphaList(int alpha)
        {
            alphaDdl.Items.Clear();
            for (int i = 1; i <= 10; i++)
            {
                int current = i * 10;
                ListItem item = new ListItem();
                item.Text = current.ToString();
                if (current == alpha)
                {
                    item.Selected = true;
                }
                alphaDdl.Items.Add(item);
            }
        }
       
        /// <summary>
        /// 绑定分类;
        /// </summary>
        /// <param name="id"></param>
        private void bindCategoryList(int id)
        {
            CategoryDdl.Items.Clear();
            List<Category> categoryList = new Category().selectList();
            foreach (Category category in categoryList)
            {
                ListItem item = new ListItem();
                item.Text = category.Name;
                item.Value = category.Id.ToString();
                if (id == category.Id)
                {
                    item.Selected = true;
                }
                CategoryDdl.Items.Add(item);
            }

        }

        /// <summary>
        /// 取得相对路径;
        /// </summary>
        /// <param name="fullPath"></param>
        /// <returns></returns>
        private string getUserBookDirectory(bool fullPath)
        {
            string path = string.Format("{0}/{1}/", userSession.Uid, bookId);
            if (fullPath)
            {
                path = Server.MapPath(string.Format("../{0}{1}", Config.UserBookSavePath, path));
            }
            return path;
        }


        /// <summary>
        /// 保存背景图;
        /// </summary>
        private void savePicture()
        {
            string path;
            if (!string.IsNullOrEmpty(thumbFileup.FileName))
            {
                if (thumbFileup.PostedFile.ContentLength < 10 || thumbFileup.FileName.Length < 5)
                {
                    errorLb.Text = "<p>提示:封面图不符合</p>";
                }
                else
                {
                    ImageGriphics imageGriphics = new ImageGriphics(thumbFileup.PostedFile.InputStream);
                    imageGriphics.OutputSize = Config.BookThumbSize;
                    
                    path = getUserBookDirectory(true) + "thumb.jpg";
                    imageGriphics.GetThumbAndSave(path);
                }
            }

            if (!string.IsNullOrEmpty(bgFileup.FileName))
            {
                if (bgFileup.PostedFile.ContentLength < 10 || bgFileup.FileName.Length < 5 || bgFileup.PostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0)
                {
                    errorLb.Text = "<p>提示:背景图不符合</p>";
                    return;
                    //throw new Exception("不符");
                }
                else if (bgFileup.PostedFile.ContentLength > 1024 * 1024 * 2)
                {
                    errorLb.Text = "<p>提示:背影图已超过2M.</p>";
                    return;
                }
                else
                {
                    ImageGriphics imageGriphics = new ImageGriphics(bgFileup.PostedFile.InputStream);
                    if (imageGriphics.InputImage.Width > 1024)
                    {
                        imageGriphics.OutputSize = new Size(1024, 0);
                    }
                    else
                    {
                        imageGriphics.OutputSize = new Size(0, 0);
                    }

                    path = getUserBookDirectory(true) + "bg.jpg";
                    imageGriphics.GetThumbAndSave(path);
                }
            }
        }

        /// <summary>
        /// 更新页面;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpDateBookBtn_Click(object sender, EventArgs e)
        {
            Book book = this.bindBook();
            this.savePicture();
            bool result = book.update();
            this.bindData();
            if (!result) errorLb.Text = "更新失败";
            errorLb.Text = "已更新";
        }
    }
}